package com.scut.edu.wanyou.net;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;

import com.scut.edu.wanyou.util.Parser;
import com.scut.edu.wanyou.util.WYRequestListener;

import android.os.AsyncTask;
import android.util.Log;

public class HttpTask extends AsyncTask<WYParams, Void, Void> {
	
	private WYRequestListener listener;
	
	public HttpTask(WYRequestListener listener)
	{
		this.listener = listener;
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		listener.onStart();
	}

	@Override
	protected Void doInBackground(WYParams... arg0) {
		// TODO Auto-generated method stub
		doPostTask(arg0[0]);
		return null;
	}
	
	private void doPostTask(WYParams params)
	{
		HttpPost post = new HttpPost(params.getAction());
		List<BasicNameValuePair> list  = params.getNameValuePairs();
		try {
			post.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
			HttpResponse response = CustomHttpClient.getHttpClient().execute(post);
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
			{
				String result = EntityUtils.toString(response.getEntity(),"gbk");
				listener.onComplete(Parser.jsonToBundle(result));
			}else {
				listener.onError(new Error(response.getStatusLine().toString()));
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			listener.onException(e);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			listener.onException(e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			listener.onException(e);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			listener.onException(e);
		}
		
	}

}
